package net.servlet;


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {

	private String uploadPath; // 上传文件的目录
	private Map<String, String> params = new HashMap<String, String>();

	/**
	 * Destruction of the servlet. <br>
	 */
	
	
	/*String json = request.getParameter("data"); 
	JSONObject jsonObject = JSONObject.fromObject(data); 
	String name = jsonObject.getString('name'); 
	...... */
	
	
	@Override
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doDelete(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPut(req, resp);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 每次调用前需要初始化
		params.clear();// = new HashMap<String, String>();
		String mid = request.getParameter("username");
		if(mid == null){
			mid="username";
		}
		setUploadPath(mid);
		uploadFiles(request, response);
		// 参数的处理
		if ("uploadImg".equals(params.get("method"))) {
			// 压缩图片
			File wallpaper = new File(uploadPath + params.get("filename"));
			Image wallpaperImg = javax.imageio.ImageIO.read(wallpaper);
			BufferedImage tag = new BufferedImage(150, 105, BufferedImage.TYPE_INT_RGB);

			Graphics2D g2d = tag.createGraphics();
			g2d.drawImage(wallpaperImg, 0, 0, 150, 105, null);
			FileOutputStream out = new FileOutputStream(uploadPath + "s_" + params.get("filename"));
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
			param.setQuality(0.75f, false);
			encoder.setJPEGEncodeParam(param);
			encoder.encode(tag);
			out.close();
		}
	}

	/**
	 * 设置上传的路径
	 * 
	 * @param method
	 * @return void
	 * @since v 1.0
	 */
	private void setUploadPath(String mid) {
			String prjPath = getServletContext().getRealPath("/");
			String _prjname = getServletContext().getContextPath();
			String prjname = _prjname.replaceAll("/", "");
			uploadPath = prjPath.replace(prjname, "ROOT") + "photos/" + mid + "/";
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists()) {
			uploadFile.mkdirs();
		}
	}

	/**
	 * 处理文件上传和参数读取
	 * 
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @return void
	 * @since v 1.0
	 */
	private void uploadFiles(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String encoding = request.getCharacterEncoding();
		try {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding(encoding);
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) {
				FileItem fi = i.next();
				String fileName = fi.getName();
				if (null != fileName) { // 对文件的处理
					File fullFile = new File(fi.getName());
					File savedFile = new File(uploadPath, fullFile.getName());
					fi.write(savedFile);
					if (fileName.indexOf('\\') > -1) {
						fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);
					}
					InputStream inputStream = new FileInputStream(uploadPath + fileName);
					inputStream.close();
					String newFileName =  fileName.substring(fileName.indexOf('.'));
					params.put("orgname", fileName);
					params.put("filename", newFileName);
					// savedFile.delete();
					savedFile.renameTo(new File(uploadPath + newFileName));
				} else { // 对其他Field的处理
					params.put(fi.getFieldName(), fi.getString(encoding));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init() throws ServletException {
		if (null == uploadPath) {
			uploadPath = getServletContext().getRealPath("/") + "temp/";
		}
		// uploadPath = Constant.appPath + "temp/";
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists()) {
			uploadFile.mkdirs();
		}
	}
}
